package controller

import (
	"apitestAfterGo/common"
	"apitestAfterGo/domain"
	"apitestAfterGo/dto"
	"apitestAfterGo/service"
	"apitestAfterGo/utils"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

type LoginController struct {
}

func (l *LoginController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("POST", "/login", "Login")
	b.Handle("POST", "/register", "Register")
	b.Handle("POST", "/password", "RePassword")
}

// 登录路由

func (l *LoginController) Login(loginDto dto.LoginDto) common.Result {
	template, err := service.UserServiceImpl.Login(loginDto.Username)
	if err != nil || template.IsActive == 0 {
		return utils.Error(common.GetResult(3).Code, common.GetResult(3).Msg)
	}
	encryptCode := utils.AesDecrypt(template.Password, template.Salt)
	if encryptCode == loginDto.Password {
		tokenString, _ := utils.GetTokenString(&template)
		return utils.Success(iris.Map{
			"user_id": template.Id,
			"token":   tokenString,
		}, "登陆成功！")
	} else {
		return utils.Error(common.GetResult(5).Code, common.GetResult(5).Msg)
	}
}

func (l *LoginController) Register(loginDto dto.LoginDto) common.Result {
	salt := utils.GetRandomStrings(16)
	encrypt := utils.AesEncrypt(loginDto.Password, salt)
	user := domain.User{Password: encrypt, Username: loginDto.Username, Salt: salt, IsActive: 0, CreateBy: "root", UpdateBy: "root"}
	_, err := service.UserServiceImpl.Register(user)
	if err != nil {
		return utils.Error(common.GetResult(4).Code, common.GetResult(4).Msg)
	}
	return utils.Success(nil, "注册成功！")
}

func (l *LoginController) RePassword(loginDto dto.LoginDto) common.Result {
	salt := utils.GetRandomStrings(16)
	encrypt := utils.AesEncrypt(loginDto.Password, salt)
	user := domain.User{Password: encrypt, Username: loginDto.Username, Salt: salt}
	_, err := service.UserServiceImpl.UpdatePasswordByUsername(user)
	if err != nil {
		return utils.Error(common.GetResult(4).Code, common.GetResult(4).Msg)
	}
	return utils.Success(nil, "修改密码成功！")
}

//func LoginInit(app *iris.Application) {
//	loginAPI := app.Party("/")
//	m := mvc.New(loginAPI)
//	m.HandleError(utils.ValidateHandler)
//	m.Handle(new(LoginController))
//}
